package org.six11.olive3.server;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * 
 * @author Gabe Johnson <johnsogg@cmu.edu>
 */
public abstract class WebActionHandler {

  private String jspPage;
  protected WebActionServlet webActionServlet;

  protected WebActionHandler(String jspPage, WebActionServlet webActionServlet) {
    this.jspPage = jspPage;
    this.webActionServlet = webActionServlet;
  }

  abstract public void service(HttpServletRequest req, HttpServletResponse resp,
      ServletContext context) throws ServletException, IOException;

  protected void go(HttpServletRequest req, HttpServletResponse resp, ServletContext context)
      throws ServletException, IOException {
    forwardTo(jspPage, req, resp, context);
  }

  protected void forwardTo(String servletPath, HttpServletRequest req, HttpServletResponse resp,
      ServletContext context) throws ServletException, IOException {
    context.getRequestDispatcher(servletPath).forward(req, resp);
  }

  protected void redo(String actionType, HttpServletRequest req, HttpServletResponse resp,
      ServletContext context) throws ServletException, IOException {
      req.setAttribute(WebActionServlet.PARAM_ACTION, actionType);
      forwardTo(WebActionServlet.WEB_ACTION_URI, req, resp, context);
  }
  
  protected Map<String, String> getPotential(int uid) {
    String suid = "" + uid;
    Map<String, String> ret = new HashMap<String, String>();
    String rateSql = SqlStrings.COUNT_TODO_RATE;
    String sketchSql = SqlStrings.COUNT_TODO_SKETCH;
    String describeSql = SqlStrings.COUNT_TODO_DESCRIBE;
    try {
      int howMany = webActionServlet.getDbThing().getInt(rateSql, suid);
      ret.put("rate", "" + howMany);
      howMany = webActionServlet.getDbThing().getInt(sketchSql, suid);
      ret.put("sketch", "" + howMany);
      howMany = webActionServlet.getDbThing().getInt(describeSql, suid);
      ret.put("describe", "" + howMany);
    } catch (ServletException ex) {
      ex.printStackTrace();
    }
    return ret;
  }
}
